package main

import (
	"beegoProject/middleware"
	_ "beegoProject/models"
	_ "beegoProject/routers"
	"beegoProject/utils/errmsg"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/plugins/cors"
	"strings"
	"time"
)

func main() {

	// 启用跨域	//InsertFilter是提供一个过滤函数
	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		//允许访问所有源
		AllowAllOrigins: true,
		//可选参数"GET", "POST", "PUT", "DELETE", "OPTIONS" (*为所有)   其中Options跨域复杂请求预检
		AllowMethods: []string{"GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE", "UPDATE"},
		//指的是允许的Header的种类
		AllowHeaders: []string{"*"},
		//公开的HTTP标头列表
		ExposeHeaders: []string{"Content-Length", "Content-Type", "Authorization"},
		//如果设置，则允许共享身份验证凭据，例如cookie
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))


	//启用用户登录过滤器
	beego.InsertFilter("/admin/*", beego.BeforeRouter, FilterUser)


	//添加模板函数,判断URL跳转
	_ = beego.AddFuncMap("equrl", CompareUrl)

	//添加模板函数,计算上下翻页
	_ = beego.AddFuncMap("Add", Add)

	logs.SetLogger(logs.AdapterFile, `{"filename":"logs/beego_blog.log", "maxdays":5}`)
	logs.EnableFuncCallDepth(true)

	beego.Run()
}



//用户是否登录判断的过滤函数
var FilterUser = func(ctx *context.Context) {
	tokenHeader := ctx.Request.Header.Get("Authorization")
	//fmt.Println(tokenHeader)

	if ctx.Request.RequestURI != "/admin/login" {

		//token不存在
		if tokenHeader == "" {
			code := errmsg.ERROR_TOKEN_NOT_EXIST //token不存在
			ctx.RenderMethodResult(map[string]interface{}{
				"status": code,
				"message": errmsg.GetErrmsg(code),
			})
			ctx.Redirect(302, "/login")
			return
		}

		//token字符串格式错误
		checkToken := strings.SplitN(tokenHeader, " ", 2)
		if len(checkToken) != 2 && checkToken[0] != "Bearer" {
			code := errmsg.ERROR_TOKEN_TYPE_WRONG //token字符串格式错误
			ctx.RenderMethodResult(map[string]interface{}{
				"status": code,
				"message": errmsg.GetErrmsg(code),
			})
			return
		}

		//token验证失败
		key, tCode := middleware.CheckToken(checkToken[1])
		if tCode == errmsg.ERROR {
			code := errmsg.ERROR_TOKEN_WRONG //token验证失败
			ctx.RenderMethodResult(map[string]interface{}{
				"status": code,
				"message": errmsg.GetErrmsg(code),
			})
			return
		}

		// token过期
		if time.Now().Unix() > key.ExpiresAt {
			code := errmsg.ERROR_TOKEN_RUNTIME
			ctx.RenderMethodResult(map[string]interface{}{
				"status": code,
				"message": errmsg.GetErrmsg(code),
			})
			ctx.Redirect(302, "/login")
			return
		}
	}

}


//模板函数,判断URL跳转
func CompareUrl(x, y string) bool {
	x1 := strings.Trim(x, "/")
	y1 := strings.Trim(y, "/")
	return (strings.Compare(x1, y1) == 0)
}


//模板函数,计算上下翻页
func Add(a int,b int) int{
	return a+b
}